global.base_dir = __dirname;

global.abs_path = function(path) {
  return base_dir + path;
};

global.include = function(file) {
  return require(abs_path(file));
};

// Require the framework and instantiate it
const _ = require('lodash');
const path = require('path');
const fastify = require('fastify')({ logger: true, ignoreTrailingSlash: true });
const SystemStatus = include('/modules/system_status');

fastify.use(require('cors')());

const databases = SystemStatus.getDatabase();
_.each(databases, function(db) {
  console.log(`\n\n设置数据库 ${db.type} ${db.name} ${db.url}`);
  if (db.type == 'mongodb') {
    fastify.register(require('fastify-mongodb'), { url: db.url, name: db.name });
  } else if (db.type == 'mysql') {
    fastify.register(require('fastify-mysql'), { promise: true, connectionString: db.url });
  } else {
    fastify.error('设置数据库出错');
    process.exit(2);
  }
});

fastify.register(require('fastify-formbody'));
fastify.register(require('fastify-sensible'));
fastify.register(require('fastify-favicon'));
fastify.register(require('fastify-static'), {
  root: path.join(__dirname, 'public'),
  prefix: '/public/', // optional: default '/'
});

fastify.get('/paopai_record', function(req, reply) {
  reply.sendFile('index.html');
});

fastify.get('/static/*', function(req, reply) {
  reply.sendFile(req.raw.url);
});

// TODO 实际需要考虑如果有多个用户在同一个局域网则怎么处理
// TODO 通过 benchmark 计算出一个合理范围
fastify.register(require('fastify-rate-limit'), {
  max: 1000,
  timeWindow: '1 minute',
  whitelist: ['127.0.0.1'],
});

fastify.register(include('/plugins'));
fastify.register(include('/models'));
fastify.register(include('/plugins/jobs'));

// 其他插件需要比路由先加载, 才能被路由调用
fastify.register(include('/routes'));

const start = async () => {
  try {
    await fastify.listen(4000, '0.0.0.0');
    console.log(`server listening on ${fastify.server.address().port}`);
  } catch (err) {
    console.log(err);
    process.exit(1);
  }
};

start();
